from PySide import QtGui
import pickle
import b_data

extension = ["*.ts", ".ts"]

class FileIO(QtGui.QWidget):
	def __init__(self, parent):
		super(FileIO, self).__init__()
		self.parent = parent
		self.initFile()
		self.initUI()
		
	def initFile(self):
		self.filename = "Untitled"
		self.saved = False
		self.exists = False
		self.directory = None
	
	def initUI(self):
		self.filedialog = QtGui.QFileDialog(self)
		self.filedialog.setGeometry(300, 200, 400, 200)
	
	def makeWindowTitle(self):
		title = "tensile-structures - " + self.filename
		if self.saved is False:
			title = title + "*"
		return title
	
	def fileNew(self):
		self.initFile()
		del self.parent.data
		self.parent.data = b_data.Data()
		self.parent.statusBar().showMessage("Here we go again")
		self.parent.editsettings.updateSettings()
		self.parent.updateAll("ALL")
	
	def fileSaveAs(self):
		name, ext = self.filedialog.getSaveFileName(self, "Save As...", self.directory, extension[0])
		if len(name) != 0:
			self.filename = self.checkFileName(name)
			self.saved = True
			self.parent.setWindowTitle(self.makeWindowTitle())
			openfile = open(self.filename, "w")
			pickle.dump(self.parent.data, openfile, -1)
			openfile.close()
			self.exists = True
			self.parent.statusBar().showMessage("File Saved")
		else:
			self.parent.statusBar().showMessage("Save Cancelled")
	
	def fileSave(self):
		if self.exists:
			openfile = open(self.filename, "w")
			pickle.dump(self.parent.data, openfile, -1)
			openfile.close()
			self.saved = True
			self.parent.statusBar().showMessage("File Saved")
		else:
			self.fileSaveAs()
		
	def fileOpen(self):
		name, ext = self.filedialog.getOpenFileName(self, "Open File", self.directory, extension[0])
		if len(name) != 0:
			self.filename = name
			self.saved = True
			self.parent.setWindowTitle(self.makeWindowTitle())
			openfile = open(self.filename, "r")
			self.parent.data = pickle.load(openfile)
			openfile.close()
			self.exists = True
			self.parent.statusBar().showMessage("File Opened")
			self.parent.editsettings.updateSettings()
			self.parent.updateAll("ALL")
		else:
			self.statusBar().showMessage("Open Cancelled")
	
	def checkFileName(self, name):
		if not name.endswith(extension[1]):
			return name + extension[1]
		return name
	
	def setDefaultDirectory(self):
		self.directory = self.filedialog.getExistingDirectory(self, "Select Default Directory", self.directory)
